package arithmetic.functionTest;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

import com.google.common.collect.Lists;

/**
 * @author jiangfeng
 * Created on 2020-04-10
 */
public class TestPredicate {

    public static void main(String[] args) {

        // 接收一个泛型,返回ture和false
        Predicate<String> p = o -> o.isEmpty();
        System.out.println(p.test("3"));
        System.out.println(p.test(""));
        System.out.println(p.test(" "));

        // 例如Collectors中的filter就是使用predicate
        ArrayList<Integer> integers = Lists.newArrayList(12, 4, 45, 32, 6, 3, 1, 2, 5, 2);


        List<Integer> collect = integers.stream().filter(a -> a > 2).collect(Collectors.toList());
        System.out.println(collect);


        // 常见用法,  实现打印一定条件的元素 (意义:提高灵活性,抽象性)
        filterPrint(integers,i->i%2==0);
        filterPrint(integers,i->i%2==1);
        filterPrint(integers,i->i>10);

    }

    public static void filterPrint(List<Integer> l, Predicate<Integer> predicate) {
        for (Integer integer : l) {
            if (predicate.test(integer)) {
                System.out.print(integer);
                System.out.print(" ");
            }
        }
        System.out.println();

    }
}


